/**
 * auth: zhuqingwen
 */
function ini_set() {
    ws = new WebSocket("ws://" + document.domain + ":7272");
    ws.onopen = function (){
    	var init_data = '{"type":"new_client", "token":"' + token + '"}';
    	ws.send(init_data);
    };
    ws.onmessage = onMessage;
    ws.onclose = function () {

    };
    ws.onerror = function () {
    	console.log('Connect Socketserver Failure');
    };

    //50秒发送一次心跳
    pingInterval(50000);
    getMessage(1);
}

//定时发送心跳数据
function pingInterval(time = 50000)
{
    setInterval(function () {
      var ping = '{"type":"ping","token":"'+token+'"}';
      ws.send(ping);
    }, time);
}


function onMessage(response)
{
     var msg = evil(response.data);
     console.log(msg);
     switch (msg.msg_type)
     {

        case "new_client":
            if(msg.client_flag == 'all_client')
            {
                client_list = msg['client_list'];
                var user_list_box = $("#user-nav1-content");
                user_list_box.empty();
                var client = '';
                $.each(client_list, function(client_index, client_info){
                    client+='<li class="client-user-info chose-client" client_id="'+client_info['client_id']+'">';
                    client+='<img class="user-content-img" src="'+client_info['avatar']+'" >';
                    client+='<div class="user-content-div">';
                    client+='<p class="user-content-name">'+client_info['user_name']+'</p>';
                    client+='<img class="user-content-pic" src="'+getRoleIcon(client_info['user_role'])+'">';
                    client+='</div>';
                    client+='</li>';
                })
                user_list_box.append(client);
            }else{
                var client = '';
                client+='<li class="client-user-info chose-client" client_id="'+msg.client_id+'">';
                client+='<img class="user-content-img" src="'+msg.avatar+'" >';
                client+='<div class="user-content-div">';
                client+='<p class="user-content-name">'+msg.user_name+'</p>';
                client+='<img class="user-content-pic" src="'+getRoleIcon(msg.user_role)+'">';
                client+='</div>';
                client+='</li>';
                $("#user-nav1-content").append(client);
                online_client_length = $("#user-nav1-content li").length;
                if(online_client_length>100)
                {
                    $("#user-nav1-content li:last-child").remove();
                }
            }
            $('#online-count').text('('+msg.client_nums+')');
            $('#top-online-count').text(msg.client_nums);
            showService(msg);
            break;

        case 'message':
            showMessage(msg);
            break;

        case 'recall_msg':
            if(msg.from_token != token)
            {
                $(".client-user-info[msg_id='"+msg.msg_id+"']").remove();
            }
            break;

        case 'change_live':
            $('.center-nav-teacher').text('主讲：'+msg.teacher_name);
            $('.center-nav-img').attr('src',msg.teacher_avatar);
            break;

        case 'close_client':
            $("#user-nav1-content li[client_id='"+msg.client_id+"']").remove();
            $('#online-count').text('('+msg.client_nums+')');
            $('#top-online-count').text(msg.client_nums);

            $("#user-nav2-content li[client_id='"+msg.client_id+"']").remove();
            var service_length = $("#user-nav2-content li").length;
            $('#server-count').text('('+service_length+')'); 
            break;

        case 'service_login':
            showService(msg);
            break;
     }
}


function sendMessage() {
    var content = $('#message_content').html(),
    to_client   = $('#to_client').val(),
    to_name     = $('#to_name').val();
    if($.trim(content).length>0)
    {
        $('.send').attr({"disabled":"disabled"});
        var message_data = {};
        message_data['type'] = 'message';
        message_data['to_client'] = to_client;
        message_data['to_name']   = to_name;
        message_data['content']   = content;
        message_data['token']     = token;
        ws.send(JSON.stringify( message_data ));
        setInterval(function()
        {
            $('.send').removeAttr("disabled");
        },1500);
        resetForClient();
    }else{
        //alert('请输入内容！');
    }
}

function getMessage(page)
{
    $.ajax({
        type: "POST",
        url: "/index/getMessage",
        data: {room_id:room_id, page:page},
        dataType: "json", 
        success: function(response){
            if(!response)return false;
            $.each(response, function(client_index, client_info){
                showMessage(client_info);
            })          
        }
    });
}

var page_up = 1;
$('.get_more_msg').click(function(){
    var page = $(this).attr('data-page');
    page_up++;
    getMessage(page_up);
 })

function showMessage(data)
{
    var msg = '';
    msg+='<li class="client-user-info" msg_cache_index="'+data.msg_cache_index+'" from_user_id="'+data.from_user_id+'" msg_id="'+data.msg_id+'" from_token="'+data.from_token+'">';
    msg+='<img class="meet-img" src="'+data.from_avatar+'">';
    msg+='<img class="meet-pic" src="'+getRoleIcon(data.user_role)+'">';
    msg+='<a href="javascript:void(0)"><span class="meet-name chose-client">'+data.from_name+'</span></a>';
    msg+='<span class="meet-time">'+data.date+'</span>';
    msg+='<div class="meet-msg">'+data.content+'</div>';
    msg+='<div class="message-menu">';
    msg+='<ul>';
    if(data.from_token == token)
    {
        msg+='<li><button class="layui-btn layui-btn-xs recall_msg">撤回</button></li>';
    }
    msg+='</ul>';
    msg+='</div>';  
    msg+='<div style="clear: both;"></div>';
    msg+='</li>';
    $('.right-msg-meet').append(msg);
    scrollBottom();
}

//显示客服
function showService(msg)
{
    var service = '';
    $.each(msg.service_list, function(client_index, client_info){
        service+='<li service_id="'+client_info['service_id']+'" client_id="'+client_info['client_id']+'">';
        service+='<img class="user-content-img" src="'+client_info['service_avatar']+'" >';
        service+='<div class="user-content-div">';
        service+='<p class="user-content-name">'+client_info['service_name']+'</p>';
        service+='<img class="user-content-pic" src="/static/images/kefu.png">';
        service+='<a href="javascript:void(0)" class="qq-chat chat_online_server" service_id="'+client_info['service_id']+'">';
        service+='<div class="QQ">在线客服</div>';
        service+='</a>';
        service+='</div>';
        service+='</li>';
    })
    $('#user-nav2-content').append(service);
    var service_length = $("#user-nav2-content li").length;
    $('#server-count').text('('+service_length+')'); 
}


layui.use(['layer','form'], function(){
    var layer = layui.layer, form   = layui.form;
    //撤回消息
    $(document).on('click','.recall_msg',function () {
        var msg_cache_index = $(this).parents('.client-user-info').attr('msg_cache_index'),
        from_user_id   = $(this).parents('.client-user-info').attr('from_user_id'),
        msg_id         = $(this).parents('.client-user-info').attr('msg_id'),
        from_token     = $(this).parents('.client-user-info').attr('from_token');
        var this_element = $(this);
        if(msg_cache_index)
        {
            $.ajax({
                type: "POST",
                url: "/index/recall_message",
                data: {msg_cache_index:msg_cache_index, from_user_id:from_user_id, from_token:from_token, msg_id:msg_id},
                dataType: "json", 
                success: function(response){
                   if(response.code == 200)
                   {
                        this_element.text('已撤回');
                        this_element.addClass('layui-btn-disabled');
                   }else{
                        layer.msg(response.msg);
                        return false;
                   }           
                }
            });
        }
    })
})

/*
*打开客服窗口
 */
$(document).on('click','.chat_online_server',function () {
    var service_id = $(this).attr('service_id'),
        service_avatar = $(this).parent().parent().find('.user-content-img').attr('src'),
        service_name = $(this).parent().find('.user-content-name').text();
    layer.open({
        area: ['600px', '522px'],
        scrollbar: false,
        title: false,
        skin: 'layui-layer-setmybg',
        type:2, 
            content: ['/services/open_service?token='+token+'&service_id='+service_id+'&service_name='+service_name+'&service_avatar='+service_avatar,'no'] 
    });
})



function evil(fn) {
    var Fn = Function;  
    return new Fn('return ' + fn)();
}


function resetForClient()
{
    $('#message_content').html('');
    $('#to_user_client').val('all');
    $('#to_user_name').val('大家');
    $('#to_client').text('大家');
    disableSend();
}

function disableSend()
{
    $('.send').attr("disabled", true); 
    $('#message_content').attr("contenteditable", false); 
    setTimeout('reinstatementSend()', 2000); 
}

function reinstatementSend()
{
    $('.send').removeAttr("disabled");
    $('#message_content').attr("contenteditable", true); 
}

function scrollBottom()
{
    $('.right-msg-meet').scrollTop($('.right-msg-meet')[0].scrollHeight);
    msg_length = $(".client-user-info").length;
    if(msg_length>40)
    {
        $('.client-user-info:first').remove();
    }
}